﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TSV.Models;
using System.Collections;
using System.Net.Mail;
using System.Text;
using System.Net.Mime;
using System.DirectoryServices;
using System.Globalization;
using System.Resources;
using System.IO;
using System.Configuration;
using TSV.Library.Utils;
namespace TSV.Library.Common
{
    public class CommonFunc
    {
        public static string ShowActiveImage(object obj)
        {
            string str = "<span class=\"{0}\"></span>";
            return string.Format(str, (obj != null && (bool)obj) ? "iactive" : "iinactive");
        }

        //public static bool SendMail(string stTo, string stCC, string stBCC, string stSubj, string stBody, System.Web.Mail.MailPriority pri)
        //{
        //    System.Web.Mail.MailMessage objEmail = new System.Web.Mail.MailMessage();
        //    objEmail.BodyFormat = MailFormat.Html;
        //    objEmail.From = Constants.CRM_MAIL_FROM;

        //    objEmail.To = stTo;
        //    objEmail.Cc = stCC;
        //    objEmail.Bcc = stBCC;
        //    objEmail.Subject = stSubj;
        //    objEmail.Body = stBody;
        //    objEmail.Priority = pri;
        //    SmtpMail.SmtpServer = Constants.SMTP_MAIL_SERVER;
        //    try
        //    {
        //        SmtpMail.Send(objEmail);
        //    }
        //    catch
        //    {
        //        return false;
        //    }

        //    return true;
        //}

        public static string GetCandidateStatus(int status)
        {
            switch (status)
            {
                case (int)CandidateStatus.Available:
                    return "Available";
                case (int)CandidateStatus.Failed:
                    return "Failed";
                case (int)CandidateStatus.Interviewing:
                    return "Interviewing";
                case (int)CandidateStatus.Passed:
                    return "Passed";
                case (int)CandidateStatus.Unavailable:
                    return "Unavailable";
                case (int)CandidateStatus.Waiting:
                    return "Waiting";

            }
            return "";
        }





        public static string ButtonEdit(string actionUrl)
        {
            return "<input type=\"button\" class=\"icon edit\" title=\"Cập nhật\" onclick=\"window.location = '" + actionUrl + "'\" />";
        }
        public static string ButtonEditPopup(string actionUrl,string title,int width)
        {
            string onclick = string.Format("JS_LIB.popup('{0}','{1}',{2});", actionUrl, title, width);
            return "<input type=\"button\" class=\"icon edit\" title=\"Cập nhật\" onclick=\"" + onclick + "\" />";
        }
        public static string Link(string id, string actionUrl, string display, bool haveTooltip)
        {
            if (haveTooltip)
            {
                return "<a id=" + id + " class='showTooltip' href='" + actionUrl + "'>" + display + "</a>";
            }
            else
            {
                return "<a id=" + id + "  href='" + actionUrl + "'>" + display + "</a>";
            }
        }

        public static string Button(string css, string title, string action)
        {
            return "<input type='button' class='icon " + css + "' title='" + title + "' onclick=\"" + action + "\" />&nbsp;";
        }

        #region phihung.nguyen

        /// <summary>
        /// Split File For Display,Download
        /// </summary>
        /// <param name="originalString"></param>
        /// <returns></returns>
        public static string SplitFileName(string originalString, string path, bool isLimit)
        {

            string link = string.Empty;
            string outputFile = string.Empty;
            if (!string.IsNullOrEmpty(originalString))
            {
                string[] arrLink = originalString.TrimEnd(Constants.FILE_CHAR_PREFIX).Split(Constants.FILE_CHAR_PREFIX);//Split File
                foreach (string arr in arrLink)
                {
                    int lastCharWithExtension = arr.LastIndexOf('.');
                    string fileWithExtension = arr.Remove(lastCharWithExtension, arr.Length - lastCharWithExtension);
                    string ext = arr.Substring(lastCharWithExtension);
                    int indexChar = fileWithExtension.LastIndexOf('.');
                    string fileName = fileWithExtension.Remove(indexChar, fileWithExtension.Length - indexChar);
                    string fileView = fileName + ext;
                    link += "<a href='#' title='" + fileView + "' onClick=\"JS_LIB.downLoadFile('" + path + arr + "','" + fileName + "')\" >" + (isLimit ? FileDisplay(fileView) : fileView) + "</a>" + " <br />";
                }
            }
            return link;
        }

        /// <summary>
        ///  Split File For Display,Download When Edit
        /// </summary>
        /// <param name="originalString"></param>
        /// <param name="path"></param>
        /// <param name="table"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string SplitFileNameForView(string originalString, string path, string table, string id, string hidField)
        {

            string link = string.Empty;
            string outputFile = string.Empty;
            int y = 0;
            if (!string.IsNullOrEmpty(originalString))
            {
                string[] arrLink = originalString.TrimEnd(Constants.FILE_CHAR_PREFIX).Split(Constants.FILE_CHAR_PREFIX);
                foreach (string arr in arrLink)
                {
                    int lastCharWithExtension = arr.LastIndexOf('.');
                    string fileWithExtension = arr.Remove(lastCharWithExtension, arr.Length - lastCharWithExtension);
                    string ext = arr.Substring(lastCharWithExtension);
                    int indexChar = fileWithExtension.LastIndexOf('.');
                    string fileName = fileWithExtension.Remove(indexChar, fileWithExtension.Length - indexChar);
                    string fileView = fileName + ext;
                    link += "<tr id='row_upload" + y + "'>" +
                                "<td class='label'>Attachment</td>" +
                                "<td id='contentFile" + y + "' class='input'>" +
                                    "<a id='link" + y + "' title='" + fileView + "' onClick=\"JS_LIB.downLoadFile('" + path + arr + "','" + fileName + "')\">" + fileView + "</a> " +
                                "</td>" +
                                "<td id='contentButton" + y + "'>" +                        
                                    "<button  type='button'  title='Remove Contract' onclick=\"return JS_LIB.removeMultiFile('" + arr + "','" + hidField + "','" + y + "','" + table + "');\" class='icon minus'></button>" +
                                "</td>" +
                            "</tr>";
                    y++;
                }
            }
            else
            {
                link += "<tr id='row_upload0'>" +
                            "<td class='label'>Attachment</td>" +
                            "<td id='contentFile0' class='input'>" +
                                "<input type='file' name='file' /></td>" +
                            "<td id='contentButton" + y + "'>" +
                                "<button type='button' onclick='return RemoveRow(this);' class='icon minus' id='0'  title='Remove Contract' ></button>" +
                            "</td>" +
                        "</tr>";
            }
            return link;
        }

        public static string FileDisplay(string originalFile)
        {
            if (originalFile.Length > Constants.FILE_NAME_VIEW)
            {
                int charIndex = originalFile.Length - originalFile.LastIndexOf('.');
                string ext = originalFile.Substring(originalFile.Length - charIndex);
                int fileview = originalFile.Length - Constants.FILE_NAME_VIEW;
                originalFile = originalFile.Remove(Constants.FILE_NAME_VIEW, fileview) + ".." + ext;
            }
            return originalFile;
        }



        #endregion

        #region (Tuan.Minh.Nguyen)=> Function Get Control Value Support Eform

        #endregion

        #region ==>Tuan.minh.nguyen (Functions support Active Directory and send Meeting request email)
        public static bool SendMeetingRequest(string start, string end, string location, string formMail, string fromName, string subject, string decs, string toMail)
        {

            SmtpClient sc = new SmtpClient();
            sc.Host = Constants.SMTP_MAIL_SERVER;
            System.Net.Mail.MailMessage msg = new System.Net.Mail.MailMessage();
            msg.From = new MailAddress(formMail, fromName);

            string[] to = toMail.Trim().Split(';');
            foreach (string strTo in to)
            {
                if (!string.IsNullOrWhiteSpace(strTo))
                    msg.To.Add(new MailAddress(strTo));
            }

            msg.Subject = subject;
            msg.Body = decs.Replace("\n", "<br/>");

            StringBuilder str = new StringBuilder();
            str.AppendLine("BEGIN:VCALENDAR");
            str.AppendLine("PRODID:-//Microsoft Corporation//Outlook 11.0 MIMEDIR//EN");
            str.AppendLine("VERSION:2.0");
            str.AppendLine("METHOD:REQUEST");
            str.AppendLine("BEGIN:VEVENT");
            str.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", DateTime.Parse(start).ToUniversalTime()));
            str.AppendLine(string.Format("DTSTAMP:{0:yyyyMMddTHHmmssZ}", DateTime.Now));
            str.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", DateTime.Parse(end).ToUniversalTime()));
            str.AppendLine("LOCATION:" + location);
            str.AppendLine(string.Format("UID:{0}", Guid.NewGuid()));
            str.AppendLine(string.Format("DESCRIPTION:{0}", msg.Body));
            str.AppendLine(string.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body));
            str.AppendLine(string.Format("SUMMARY:{0}", msg.Subject));
            str.AppendLine(string.Format("ORGANIZER;NAME=\"{0}\":MAILTO:{1}", msg.From.Address, msg.From.DisplayName));
            str.AppendLine(string.Format("ATTENDEE;CN=\"{0}\";RSVP=TRUE:mailto:{1}", msg.To[0].DisplayName, msg.To[0].Address));
            str.AppendLine("BEGIN:VALARM");
            str.AppendLine("TRIGGER:-PT15M");
            str.AppendLine("ACTION:DISPLAY");
            str.AppendLine("DESCRIPTION:Reminder");
            str.AppendLine("END:VALARM");
            str.AppendLine("END:VEVENT");
            str.AppendLine("END:VCALENDAR");

            System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType("text/calendar");
            ct.Parameters.Add("method", "REQUEST");
            AlternateView avCal = AlternateView.CreateAlternateViewFromString(str.ToString(), ct);
            msg.AlternateViews.Add(avCal);

            AlternateView body = AlternateView.CreateAlternateViewFromString(msg.Body, new ContentType("text/html"));
            msg.AlternateViews.Add(body);
            try
            { sc.Send(msg); return true; }
            catch { return false; }

        }

        public static DirectoryEntry GetDomainUser(string loginName)
        {

            System.DirectoryServices.ActiveDirectory.Domain thisDomain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain();

            DirectoryEntry deRoot = new DirectoryEntry("LDAP://" + thisDomain.Name);
            DirectorySearcher deSrch = new DirectorySearcher(deRoot);

            deSrch.Filter = "(SAMAccountName=" + loginName + ")";
            deSrch.PropertiesToLoad.Add("distinguishedName");
            deSrch.PropertiesToLoad.Add("cn");
            deSrch.PropertiesToLoad.Add("SAMAccountName");


            SearchResult result = deSrch.FindOne();
            DirectoryEntry directoryEntry = result.GetDirectoryEntry();

            return directoryEntry;
        }



        public static SearchResultCollection GetDomainUserList(string str)
        {

            System.DirectoryServices.ActiveDirectory.Domain thisDomain = System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain();

            DirectoryEntry deRoot = new DirectoryEntry("LDAP://" + thisDomain.Name);
            DirectorySearcher deSrch = new DirectorySearcher(deRoot);

            deSrch.Filter = "(SAMAccountName=" + str + "*)";
            deSrch.SearchScope = SearchScope.Subtree;
            deSrch.ReferralChasing = ReferralChasingOption.All;
            deSrch.PropertiesToLoad.Add("distinguishedName");
            deSrch.PropertiesToLoad.Add("cn");
            deSrch.PropertiesToLoad.Add("SAMAccountName");
            deSrch.PropertiesToLoad.Add("mail");
            deSrch.PropertiesToLoad.Add("userPrincipalName");
            deSrch.PropertiesToLoad.Add("displayName");
            SearchResultCollection Results = deSrch.FindAll();
            return Results;

        }


        public static string GetEmailByLoginName(string loginName)
        {
            return GetDomainUser(loginName).Properties[GetDomainUserProperty(DomainUserProperty.OutlookEmail)][0].ToString();
        }

        public static string GetLoginNameByEmail(string email)
        {
            string value = string.Empty;
            if (!string.IsNullOrEmpty(email))
            {
                DirectoryEntry dentry = new DirectoryEntry("LDAP://logigear.com");
                DirectorySearcher deSearch = new DirectorySearcher(dentry);

                deSearch.Filter = "(mail=" + email + ")";

                SearchResult result = deSearch.FindOne();

                if (result != null)
                {
                    value = result.Properties[GetDomainUserProperty(DomainUserProperty.LoginName)][0].ToString();
                }
            }
            return value;
        }

        public static string GetDomainUserProperty(DomainUserProperty property)
        {
            switch (property)
            {
                case DomainUserProperty.AccountName:
                    return "Name";
                case DomainUserProperty.ChangedDate:
                    return "whenChanged";
                case DomainUserProperty.Company:
                    return "company";
                case DomainUserProperty.CreatedDate:
                    return "whenCreated";
                case DomainUserProperty.Department:
                    return "department";
                case DomainUserProperty.DisplayName:
                    return "displayName";
                case DomainUserProperty.LoginName:
                    return "sAMAccountName";
                case DomainUserProperty.OutlookEmail:
                    return "mail";
                case DomainUserProperty.SeatCode:
                    return "physicalDeliveryOfficeName";
                case DomainUserProperty.Title:
                    return "title";
                default:
                    return "";
            }
        }


        #endregion

        #region Huy.Ly added by 16-Nov-2010


        /// <summary>
        /// Encode and replace multiple line
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string SyntaxHighLight(string content)
        {
            string result = content;
            string[] keywordArray = { "public", "string", "int", "return", "double", "float" };
            string[] objectArray = { "Array", "ArrayList", "DateTime", "Object", "Int", "String", "Float", "Double" };
            string strFormat = "<span class=\"{0}\">{1}</span>";
            foreach (string keyword in keywordArray)
            {
                result = result.Replace(keyword, string.Format(strFormat, "keyword", keyword));
            }
            foreach (string keyword in objectArray)
            {
                result = result.Replace(keyword, string.Format(strFormat, "object", keyword));
            }
            return result;
        }

        #endregion

        #region Duy Hung Nguyen - String Util

        /// <summary>
        /// Sub string the content, loop to round a word 
        /// </summary>
        /// <param name="template"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string SubStringRoundWord(string template, int length)
        {
            if (!string.IsNullOrEmpty(template))
            {
                template = template.Trim();
                int maxLength = template.Length > length ? length : template.Length;
                if (template.Length > maxLength)
                {
                    while (template[maxLength - 1] != ' ' && template.Length > maxLength)
                    {
                        maxLength++;
                    }
                }
                if (template.Length > length)
                {
                    return RemoveScript(template.Substring(0, maxLength)).Replace("\n", "<br/>") + "...";
                }
                else
                {
                    return RemoveScript(template.Substring(0, maxLength)).Replace("\n", "<br/>");
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// Sub string the content, loop to round a word 
        /// </summary>
        /// <param name="template"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string SubStringRoundWordNotMultiline(string template, int length)
        {
            if (!string.IsNullOrEmpty(template))
            {
                template = template.Trim();
                int maxLength = template.Length > length ? length : template.Length;
                if (template.Length > maxLength)
                {
                    while (template[maxLength - 1] != ' ' && template.Length > maxLength)
                    {
                        maxLength++;
                    }
                }
                if (template.Length > length)
                {
                    return HttpUtility.HtmlEncode(template.Substring(0, maxLength)) + "...";
                }
                else
                {
                    return HttpUtility.HtmlEncode(template.Substring(0, maxLength));
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// Encode and replace multiple line
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static string Encode(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                return string.Empty;
            }
            else
            {
                return HttpUtility.HtmlEncode(content).Replace("\n", "<br/>");
            }
        }

        /// <summary>
        /// Remove the script
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string RemoveScript(string value)
        {
            var result = value.Replace("<script>", "").Replace("</script>", "");
            result = result.Replace("eval\\((.*)\\)", "");
            result = result.Replace("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
            result = result.Replace("\'", "&#39;");

            return result;
        }

        /// <summary>
        /// encrypt Data by Md5 type
        /// </summary>
        /// <param name="data"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string encryptDataMd5(string data, int length)
        {
            System.Security.Cryptography.MD5CryptoServiceProvider md5Hasher = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] hashedBytes;
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            hashedBytes = md5Hasher.ComputeHash(encoder.GetBytes(data));
            StringBuilder sbuilder = new StringBuilder();
            for (int i = 0; i < length; i++)
            {
                sbuilder.Append(hashedBytes[i].ToString("x2"));
            }
            return sbuilder.ToString();
        }

        #endregion

        /// <summary>
        /// Read all message from resource and paste to JS
        /// </summary>
        /// <returns></returns>
        public static string ParseResourceToJS()
        {
            StringBuilder jsConstant = new StringBuilder();
            ResourceSet rs = Resources.Message.ResourceManager.GetResourceSet(CultureInfo.CurrentCulture, true, true);
            jsConstant.AppendLine("<script type=\"text/javascript\">");
            foreach (DictionaryEntry r in rs)
            {
                jsConstant.AppendLine("\tvar " + r.Key.ToString() + " = \"" + r.Value.ToString().Replace("\"", "\\\"") + "\";");
            }
            jsConstant.AppendLine("</script>");
            return jsConstant.ToString();
        }
        /// <summary>
        /// Remove a file
        /// </summary>
        /// <param name="fileName">file url including filename</param>
        public static void RemoveFile(string fileUrl)
        {
            string serverPath = System.Web.HttpContext.Current.Server.MapPath("~");
            File.Delete(serverPath + fileUrl);
        }

        public static string SetHtmlForCKEditor(string original)
        {
            if (string.IsNullOrEmpty(original))
            {
                return string.Empty;
            }
            else
            {
                original = original.Replace("&lt;", "<");
                original = original.Replace("&gt;", ">");
            }
            return original;
        }
        /// <summary>
        /// Set Page Index of JqGrid
        /// </summary>
        /// <param name="countGrid"></param>
        /// <param name="currentPage"></param>
        /// <param name="rowNumber"></param>
        /// <returns></returns>
        #region Set Page Index
        public static int SetJqGridPageIndex(int countGrid, int currentPage, int rowNumber)
        {
            int pageIndex = 1;
            if (countGrid > rowNumber)
            {
                pageIndex = currentPage;
            }
            return pageIndex;
        }
        #endregion
//For Student card
#region Tuannguyen add 02-Mar-11
        public static string GetGender(Boolean gen)
        {
            return gen == false ? "Nữ" : "Nam";
        }
#endregion
        #region TuanNguyen 10-Apr-11
        public static int [] FixImageSize(int fixWidth,int fixHeight,string imagePhysicalPath)
        {
            int w, h;
            try
            {
                System.Drawing.Image objImage = System.Drawing.Image.FromFile(imagePhysicalPath);
                
                h = objImage.Height > fixHeight ? fixHeight : objImage.Height;
                w = objImage.Width > fixWidth ? fixWidth : objImage.Width;
            }
            catch
            {
                return new int[2] { fixWidth, fixHeight };
            }
            return new int[2] { w,h};
        }
        public static int[] ResizeImage(int oldWidth, int oldHeight, int fixWidth, int fixHeight)
        {
            double distance = (oldWidth - oldHeight);
            int width = 0;
            int height = 0;
            if (distance == 0)
                distance = 1;
            if (distance < 0)
            {
                distance *= -1;
            }
            double ratioW = oldWidth * 1.0 / distance;
            double ratioH = oldHeight * 1.0 / distance;
            //ratio = W:H
            /*Formula
             * 
             * Height = fixWidth * ratioH / ratioW
             * Width = fixHeight * ratioW / ratioH
             * 
             */

            if (oldWidth > fixWidth)
            {
                width = fixWidth;
            }
            else
            {
                width = oldWidth;
            }

            height = Convert.ToInt32(width * (ratioH / ratioW));

            if (height > fixHeight)
            {
                height = fixHeight;
                width = Convert.ToInt32(height * (ratioW / ratioH));
            }


            int[] arrWH = { width, height };
            return arrWH;
        }
        #endregion

        public static string GetMainPartnerAddress(int partnerID)
        {
            string result = string.Empty;
            PartnerAddress obj = new PartnerDao().GetMainPartnerAddressByPartnerID(partnerID);
            if (obj != null)
            {
                result = obj.Address;
            }
            return result;
        }
    }
}